// 游戏增强系统集成文件 - 确保新功能与现有系统完美整合
(function() {
    'use strict';
    
    class EnhancementIntegration {
        constructor() {
            this.integrated = false;
            this.retryCount = 0;
            this.maxRetries = 10;
        }
        
        initialize() {
            // 等待所有系统加载完成
            const checkInterval = setInterval(() => {
                if (this.areSystemsReady()) {
                    this.integrateEnhancements();
                    clearInterval(checkInterval);
                } else {
                    this.retryCount++;
                    if (this.retryCount >= this.maxRetries) {
                        console.error('增强系统集成超时');
                        clearInterval(checkInterval);
                    }
                }
            }, 1000);
        }
        
        areSystemsReady() {
            return window.gameEngine && 
                   window.player && 
                   window.levelManager && 
                   window.gameEnhancements;
        }
        
        integrateEnhancements() {
            if (this.integrated) return;
            
            console.log('🔧 开始集成游戏增强系统...');
            
            try {
                this.integrateGameEngine();
                this.integrateZombieSystem();
                this.integrateLevelSystem();
                this.integratePlayerSystem();
                this.setupSupplyDropHandling();
                this.setupCustomControls();
                
                this.integrated = true;
                console.log('✅ 游戏增强系统集成完成！');
                
                // 显示帮助信息
                this.showControlsHelp();
                
            } catch (error) {
                console.error('增强系统集成失败:', error);
            }
        }
        
        integrateGameEngine() {
            // 保存原始的update和render方法
            const originalUpdate = window.gameEngine.update.bind(window.gameEngine);
            const originalRender = window.gameEngine.render.bind(window.gameEngine);
            
            // 增强update方法
            window.gameEngine.update = function(deltaTime) {
                originalUpdate(deltaTime);
                
                // 调用增强系统更新
                if (window.gameEnhancements) {
                    window.gameEnhancements.update(deltaTime);
                }
            };
            
            // 增强render方法
            window.gameEngine.render = function() {
                originalRender();
                
                // 调用增强系统渲染
                if (window.gameEnhancements) {
                    window.gameEnhancements.render(this.ctx);
                }
                
                // 渲染增强UI信息
                this.renderEnhancementUI();
            };
            
            // 添加增强UI渲染方法
            window.gameEngine.renderEnhancementUI = function() {
                if (!window.gameEnhancements) return;
                
                const stats = window.gameEnhancements.getStats();
                const ctx = this.ctx;
                
                // 渲染连击信息
                if (stats.combo && stats.combo.current > 0) {
                    ctx.save();
                    ctx.fillStyle = '#FFFFFF';
                    ctx.font = 'bold 20px monospace';
                    ctx.textAlign = 'center';
                    ctx.fillText(`${stats.combo.current}x 连击`, 500, 50);
                    
                    if (stats.combo.multiplier > 1) {
                        ctx.fillStyle = '#FFD700';
                        ctx.font = '14px monospace';
                        ctx.fillText(`${stats.combo.multiplier}x 奖励`, 500, 70);
                    }
                    ctx.restore();
                }
                
                // 渲染闪避冷却
                if (window.gameEnhancements.dodgeSystem) {
                    const dodgeSystem = window.gameEnhancements.dodgeSystem;
                    const now = Date.now();
                    const cooldownRemaining = Math.max(0, dodgeSystem.dodgeCooldown - (now - dodgeSystem.lastDodgeTime));
                    
                    if (cooldownRemaining > 0) {
                        ctx.save();
                        ctx.fillStyle = '#FF6B6B';
                        ctx.font = '12px monospace';
                        ctx.textAlign = 'right';
                        ctx.fillText(`闪避冷却: ${(cooldownRemaining / 1000).toFixed(1)}s`, 980, 30);
                        ctx.restore();
                    } else if (!dodgeSystem.isDodging) {
                        ctx.save();
                        ctx.fillStyle = '#4ECDC4';
                        ctx.font = '12px monospace';
                        ctx.textAlign = 'right';
                        ctx.fillText('闪避准备就绪 [空格]', 980, 30);
                        ctx.restore();
                    }
                }
            };
            
            console.log('🎮 游戏引擎增强完成');
        }
        
        integrateZombieSystem() {
            // 监听僵尸死亡事件
            const originalUpdate = window.gameEngine.update.bind(window.gameEngine);
            
            let lastZombieCount = 0;
            
            window.gameEngine.update = function(deltaTime) {
                const currentZombieCount = this.zombies.length;
                
                // 检测僵尸死亡
                if (currentZombieCount < lastZombieCount) {
                    const killedCount = lastZombieCount - currentZombieCount;
                    for (let i = 0; i < killedCount; i++) {
                        window.gameEnhancements?.onZombieKilled();
                    }
                }
                
                lastZombieCount = currentZombieCount;
                
                originalUpdate(deltaTime);
                
                if (window.gameEnhancements) {
                    window.gameEnhancements.update(deltaTime);
                }
            };
            
            console.log('🧟 僵尸系统增强完成');
        }
        
        integrateLevelSystem() {
            // 增强关卡开始事件
            if (window.levelManager && window.levelManager.startLevel) {
                const originalStartLevel = window.levelManager.startLevel.bind(window.levelManager);
                
                window.levelManager.startLevel = function(levelNumber) {
                    const result = originalStartLevel(levelNumber);
                    
                    // 触发增强系统的关卡开始事件
                    if (window.gameEnhancements) {
                        window.gameEnhancements.onLevelStart();
                    }
                    
                    return result;
                };
            }
            
            console.log('🎯 关卡系统增强完成');
        }
        
        integratePlayerSystem() {
            // 增强玩家伤害检测（为闪避无敌添加保护）
            if (window.player && window.player.takeDamage) {
                const originalTakeDamage = window.player.takeDamage.bind(window.player);
                
                window.player.takeDamage = function(damage, source) {
                    // 检查闪避无敌状态
                    if (window.gameEnhancements?.dodgeSystem?.isInvulnerable()) {
                        console.log('🛡️ 闪避无敌，免疫伤害');
                        return false;
                    }
                    
                    return originalTakeDamage(damage, source);
                };
            }
            
            console.log('👤 玩家系统增强完成');
        }
        
        setupSupplyDropHandling() {
            // 增强道具拾取系统处理补给空投
            const originalUpdate = window.gameEngine.update.bind(window.gameEngine);
            
            window.gameEngine.update = function(deltaTime) {
                originalUpdate(deltaTime);
                
                // 处理补给空投拾取
                this.powerUps.forEach((powerUp, index) => {
                    if (powerUp.type === 'supply_drop' && !powerUp.collected && window.player) {
                        const distance = Math.sqrt(
                            Math.pow(powerUp.x - window.player.x, 2) + 
                            Math.pow(powerUp.y - window.player.y, 2)
                        );
                        
                        if (distance < 30) {
                            this.collectSupplyDrop(powerUp);
                            this.powerUps.splice(index, 1);
                        }
                    }
                });
                
                if (window.gameEnhancements) {
                    window.gameEnhancements.update(deltaTime);
                }
            };
            
            // 添加补给空投收集方法
            window.gameEngine.collectSupplyDrop = function(supply) {
                switch (supply.subType) {
                    case 'health':
                        if (window.player.health < window.player.maxHealth) {
                            window.player.health = Math.min(window.player.maxHealth, window.player.health + supply.amount);
                            if (window.player.updateHealthUI) window.player.updateHealthUI();
                            window.gameEnhancements?.visualEffects?.createComboText(
                                window.player.x, window.player.y, `+${supply.amount} HP`, '#00FF00'
                            );
                        }
                        break;
                    case 'ammo':
                        if (window.player.currentWeapon) {
                            window.player.currentWeapon.totalAmmo += supply.amount;
                            window.gameEnhancements?.visualEffects?.createComboText(
                                window.player.x, window.player.y, `+${supply.amount} 弹药`, '#00BFFF'
                            );
                        }
                        break;
                    case 'damage':
                        if (window.player.currentWeapon) {
                            window.player.currentWeapon.damage = Math.floor(window.player.currentWeapon.damage * supply.amount);
                            window.gameEnhancements?.visualEffects?.createComboText(
                                window.player.x, window.player.y, '伤害增强!', '#FF4500'
                            );
                        }
                        break;
                }
                
                console.log(`📦 收集补给: ${supply.subType}`);
            };
            
            console.log('📦 补给系统增强完成');
        }
        
        setupCustomControls() {
            // 设置增强键盘控制
            document.addEventListener('keydown', (e) => {
                // Ctrl+I 显示增强系统信息
                if (e.ctrlKey && e.code === 'KeyI') {
                    e.preventDefault();
                    this.showEnhancementInfo();
                }
                
                // Ctrl+H 显示控制帮助
                if (e.ctrlKey && e.code === 'KeyH') {
                    e.preventDefault();
                    this.showControlsHelp();
                }
            });
            
            console.log('⌨️ 自定义控制增强完成');
        }
        
        showEnhancementInfo() {
            if (!window.gameEnhancements) return;
            
            const stats = window.gameEnhancements.getStats();
            const info = `
🎮 游戏增强系统状态:
━━━━━━━━━━━━━━━━━━
🔥 当前连击: ${stats.combo?.current || 0}
🏆 最佳连击: ${stats.combo?.best || 0}
⚡ 奖励倍数: ${stats.combo?.multiplier || 1}x
🏃 闪避状态: ${stats.dodgeAvailable ? '准备就绪' : '冷却中'}
🌟 活跃事件: ${stats.activeEvents || 0} 个
            `;
            
            console.log(info);
            
            if (window.gameEnhancements.visualEffects) {
                window.gameEnhancements.visualEffects.createEventNotification(
                    `连击: ${stats.combo?.current || 0}x | 事件: ${stats.activeEvents || 0}`,
                    '#4ECDC4'
                );
            }
        }
        
        showControlsHelp() {
            const helpText = `
🎮 增强控制说明:
━━━━━━━━━━━━━━━━━━
🏃 [空格] - 闪避/翻滚
🔍 [Ctrl+I] - 显示增强信息
❓ [Ctrl+H] - 显示这个帮助
📊 [Ctrl+Shift+R] - 肉鸽统计
━━━━━━━━━━━━━━━━━━
✨ 新功能:
🧟 连击系统 - 快速击杀获得奖励
💥 可破坏环境 - 射击家具和爆炸桶
⚡ 动态事件 - 补给空投和特殊挑战
🛡️ 闪避无敌 - 翻滚时短暂免疫伤害
            `;
            
            console.log(helpText);
            
            if (window.gameEnhancements?.visualEffects) {
                window.gameEnhancements.visualEffects.createEventNotification(
                    '按 Ctrl+H 查看控制帮助',
                    '#FFD700'
                );
            }
        }
    }
    
    // 自动初始化
    const integration = new EnhancementIntegration();
    
    // 等待页面加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => integration.initialize(), 2000);
        });
    } else {
        setTimeout(() => integration.initialize(), 2000);
    }
    
    // 导出到全局
    window.enhancementIntegration = integration;
    
    console.log('🔧 增强系统集成器已加载');
    
})();